﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using System.Data.Services.Client;

namespace FeedReader.Shared.Data
{
    public class UsersDataSource
    {
        private UsersDataServiceContext _ServiceContext = null;

        public UsersDataSource(CloudStorageAccount storageAccount)
        {
            //var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            _ServiceContext = new UsersDataServiceContext(storageAccount.TableEndpoint.ToString(), storageAccount.Credentials);

            // Create the tables
            // In this case, just a single table.  
            storageAccount.CreateCloudTableClient().CreateTableIfNotExist(UsersDataServiceContext.UsersTableName);
        }

        public IEnumerable<UsersDataModel> Select()
        {
            var results = from c in _ServiceContext.UsersTable
                          select c;

            var query = results.AsTableServiceQuery<UsersDataModel>();
            var queryResults = query.Execute();

            return queryResults;
        }
        //public IEnumerable<UsersDataModel> SelectUser(string userid)
        //{
        //    var results = from c in _ServiceContext.UsersTable
        //                  where c.UserID ==userid
        //                  select c;

        //    var query = results.AsTableServiceQuery<UsersDataModel>();
        //    var queryResults = query.Execute();

        //    return queryResults;
        //}

        //public void Delete(UsersDataModel itemToDelete)
        //{
        //    _ServiceContext.AttachTo(UsersDataServiceContext.UsersTableName, itemToDelete, "*");
        //    _ServiceContext.DeleteObject(itemToDelete);
        //    _ServiceContext.SaveChanges();
        //}

        //public void Insert(UsersDataModel newItem)
        //{
        //    _ServiceContext.AddObject(UsersDataServiceContext.UsersTableName, newItem);
        //    _ServiceContext.SaveChanges();
        //}

        //public void SaveChanges()
        //{
        //    _ServiceContext.SaveChanges();
        //}

        public IEnumerable<UsersDataModel> Select(string userid)
        {
            var results = from c in _ServiceContext.UsersTable
                          where c.UserID == userid
                          select c;

            var query = results.AsTableServiceQuery<UsersDataModel>();
            var queryResults = query.Execute();

            return queryResults;
        }

        public void Insert(UsersDataModel user)
        {
            _ServiceContext.AddObject(UsersDataServiceContext.UsersTableName, user);
            _ServiceContext.SaveChanges();
        }
    }
}
